﻿using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.IO;
using System.Linq;

namespace SqlScriptsRunner
{
    internal static class Extention
    {
        private const int MinArrayLength = 2;
        /// <summary>
        /// Sort input array of Directories names by Prioriry using <see cref="priorityList" />
        /// </summary>
        /// <param name="directories">Directories names to sort</param>
        /// <param name="priorityList">Prioriry string collection</param>
        /// <returns></returns>
        internal static string[] SortDirectoriesByPrioriry(this string[] directories, StringCollection priorityList)
        {
            if (directories.Length < MinArrayLength || priorityList.Count < MinArrayLength)
            {
                return directories;
            }

            var resultSortedList = new List<string>();
            var tmpList = new List<string>(directories);

            foreach (var priorityDir in priorityList)
            {
                foreach (var directory in directories)
                {
                    if (string.Equals(Path.GetFileName(directory), priorityDir, StringComparison.InvariantCultureIgnoreCase))
                    {
                        resultSortedList.Add(directory);
                        tmpList.Remove(directory);
                        break;
                    }
                }
            }

            if (Properties.Settings.Default.UseOnlyRegisteredFolders && tmpList.Count > 0)
            {
                resultSortedList.AddRange(tmpList);
            }

            return resultSortedList.ToArray();
        }

        internal static bool IsRootDbDirectory(this string[] directories, StringCollection priorityList)
        {
            return directories.Length != 0 && directories.Any(d => priorityList.Contains(Path.GetFileName(d)));
        }
    }
}
